<template>
  <view class="container">
    <!-- 卡片信息 -->
    <view class="card">
      <view class="info">
        <view>📅 {{ currentDate }}</view>
        <view>👤 {{ memberInfo.name || memberInfo.username || t('order.select_member') }}</view>
        <view>🎂 {{ memberInfo.date_of_birth || t('order.not_filled') }}</view>
      </view>
      <button class="member-btn" @click="gotoMemberSelect">{{ t('order.choose_member') }}</button>
    </view>

    <!-- 可折叠表单区域 -->
    <view class="form-section">
      <view class="collapse-header row-flex" @click="formCollapsed = !formCollapsed">
        <!-- <text class="form-label">诊断信息</text> -->
        <view class="flex-spacer"></view>
        <text class="collapse-arrow">{{ formCollapsed ? '▼' : '▲' }}</text>
      </view>

      <view v-show="!formCollapsed">
        <!-- 治疗目的 多选 点击高亮 -->
        <view class="form-row">
          <view class="form-label full-width">{{ t('order.purpose') }}</view>
          <view class="select-group left-align">
            <view v-for="item in purposeOptions" :key="item" class="select-item" :class="{ selected: formData.objective_list.includes(item) }" @click="togglePurpose(item)">{{ item }}
            </view>
          </view>
        </view>
        <!-- 疼痛方式 单选 点击高亮 -->
        <view class="form-row">
          <view class="form-label full-width">{{ t('order.pain_type') }}</view>
          <view class="select-group left-align">
            <view v-for="item in painTypeOptions" :key="item" class="select-item" :class="{ selected: formData.pain_mode === item }" @click="selectPainType(item)">{{ item }}</view>
          </view>
        </view>
        <!-- 疼痛指数 单选 点击高亮 -->
        <view class="form-row">
          <view class="form-label full-width">{{ t('order.pain_index') }}</view>
          <view class="select-group left-align">
            <view v-for="item in painIndex" :key="item" class="select-item" :class="{ selected: formData.pain_value === item }" @click="selectPainIndex(item)">{{ item }}</view>
          </view>
        </view>
        <!-- 是否有困难仰卧或者俯卧 单选 点击高亮 -->
        <view class="form-row">
          <view class="form-label full-width">{{ t('order.sleep_difficulty') }}</view>
          <view class="select-group left-align">
            <view class="select-item" :class="{ selected: formData.type === true }" @click="selectSleepy('是')">{{
              t('order.common_yes') }}</view>
            <view class="select-item" :class="{ selected: formData.type === false }" @click="selectSleepy('否')">{{
              t('order.common_no') }}</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 主诉/检查/症状合并为一个折叠面板 -->
    <view class="form-section">
      <view class="collapse-header row-flex" @click="collapse.zhusuGroup = !collapse.zhusuGroup">
        <!-- <text class="form-label">主诉/检查/症状</text> -->
        <view class="flex-spacer"></view>
        <text class="collapse-arrow">{{ collapse.zhusuGroup ? '▼' : '▲' }}</text>
      </view>
      <view v-show="!collapse.zhusuGroup">
        <!-- 主诉 -->
        <view class="form-row row-flex">
          <view class="form-label">{{ t('order.main_complaint') }}</view>
          <view class="flex-spacer"></view>
          <button class="fill-helper-btn" @click.stop="gotoZhusuHelper">{{ t('order.fill_helper') }}</button>
        </view>
        <textarea v-model="formData.main_complaint" class="form-textarea" :placeholder="t('order.input_main_complaint')" />
        <!-- 检查 -->
        <view class="form-row row-flex">
          <view class="form-label">{{ t('order.inspect') }}</view>
          <view class="flex-spacer"></view>
          <button class="fill-helper-btn" @click.stop="gotoJianchaHelper">{{ t('order.fill_helper') }}</button>
        </view>
        <textarea v-model="formData.inspect" class="form-textarea" :placeholder="t('order.input_inspect')" />
        <!-- 症状 -->
        <view class="form-row row-flex">
          <view class="form-label">{{ t('order.symptom') }}</view>
          <view class="flex-spacer"></view>
          <button class="fill-helper-btn" @click.stop="gotoZhengzhuangHelper">{{ t('order.fill_helper')
          }}</button>
        </view>
        <textarea v-model="formData.symptom" class="form-textarea" :placeholder="t('order.input_symptom')" />

        <!-- 部位 -->
        <view class="form-row row-flex">
          <view class="form-label">{{ t('order.part') }}</view>
          <view class="flex-spacer"></view>
          <button class="fill-helper-btn" @click.stop="gotoBodyHelper">{{ t('order.fill_helper') }}</button>
        </view>
        <textarea v-model="formData.part" class="form-textarea" :placeholder="t('order.input_part')" />

        <!-- 治疗方法 -->
        <view class="form-row row-flex">
          <view class="form-label">{{ t('order.method') }}</view>
          <view class="flex-spacer"></view>
          <button class="fill-helper-btn" @click.stop="gotoTreatmentmethodHelper">{{ t('order.fill_helper')
          }}</button>
        </view>
        <textarea v-model="formData.method" class="form-textarea" :placeholder="t('order.input_method')" />

        <!-- 结果 -->
        <view class="form-row row-flex">
          <view class="form-label">{{ t('order.result') }}</view>
          <view class="flex-spacer"></view>
          <button class="fill-helper-btn" @click.stop="gotoResultHelper">{{ t('order.fill_helper') }}</button>
        </view>
        <textarea v-model="formData.result" class="form-textarea" :placeholder="t('order.input_result')" />

        <view class="form-row">
          <view class="form-label">{{ $t('order.plan') }}</view>

          <view style="display: flex; align-items: center; flex-wrap: wrap; gap: 8px;">
            <text>{{ $t('order.beforeDays') }}</text>

            <picker :range="daysOptions" :value="planDayIndex" @change="onPlanDayChange">
              <view class="custom-picker">
                <text>{{ formData.plan_day || '' }}</text>
                <text class="arrow">&#9662;</text>
              </view>
            </picker>

            <text>{{ $t('order.afterDays') }}</text>

            <picker :range="timesOptions" :value="planTimesIndex" @change="onPlanTimesChange">
              <view class="custom-picker">
                <text>{{ formData.plan_ce || '' }}</text>
                <text class="arrow">&#9662;</text>
              </view>
            </picker>

            <text>{{ $t('order.timesSuffix') }}</text>
          </view>
        </view>
        <!-- 补充说明 -->
        <view class="form-row">
          <view class="form-label">{{ t('order.describe') }}</view>
          <textarea v-model="formData.describe" class="form-textarea" :placeholder="t('order.input_describe')" />
        </view>
        <!-- 文档上传 -->
        <view class="form-row">
          <view class="form-label">{{ t('order.document') }}</view>
          <view class="upload-area" @click="chooseFile">
            <view v-if="!formData.files.length">{{ t('order.drag_upload') }}</view>
            <view v-else>
              <view v-for="(file, idx) in formData.files" :key="file.url" class="uploaded-file">
                <text class="file-name">{{ file.name }}</text>
                <button class="delete-btn" @click.stop="removeFile(idx)">{{ t('order.common_delete') }}</button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 产品选择区 -->
    <view v-if="shouldShowProductSelection" class="form-section">
      <view class="section-header">
        <text class="section-title">📦 {{ t('order.selected_products') }}</text>
      </view>
      
      <!-- 已选产品列表 -->
      <view v-if="selectedProducts.length > 0" class="selected-products-list">
        <view v-for="(product, index) in selectedProducts" :key="product.id" class="selected-product-item">
          <view class="product-info-group">
            <image :src="product.show_img" class="product-thumb" />
            <view class="product-info">
              <view class="product-title">{{ product.name }}</view>
              <view class="product-meta">
                <!-- <text class="product-price">￥{{ product.price }}</text> -->
                <text class="product-duration">{{ product.duration }}{{ t('order.order_minute') }}</text>
                <text class="product-type" style="font-size: 12px; color: #666; margin-left: 8px;">
                  ({{ getProductTypeText(product.type) }})
                </text>
              </view>
            </view>
          </view>
          <button class="remove-product-btn" @click="removeProduct(index)">{{ t('order.remove_product') }}</button>
        </view>
      </view>
      
      <!-- 选择产品按钮 -->
      <view class="product-selection-buttons">
        <button class="fill-helper-btn" @click="gotoProductSelect('0')" :class="{ 'disabled-btn': !formData.objective_list.includes(t('order.purpose_massage')) }">
          {{ t('order.select_massage_product') }}
        </button>
        <button class="fill-helper-btn" @click="gotoProductSelect('1')" :class="{ 'disabled-btn': !formData.objective_list.includes(t('order.purpose_acupuncture')) }">
          {{ t('order.select_acupuncture_product') }}
        </button>
      </view>
      
      <!-- 提示信息 -->
      <view v-if="!formData.objective_list.includes(t('order.purpose_massage')) && !formData.objective_list.includes(t('order.purpose_acupuncture'))" class="selection-tip">
        <text class="tip-text">💡 {{ t('order.select_purpose_tip') }}</text>
      </view>
    </view>

    <!-- 签名状态展示区 -->
    <view class="form-section">
      <view class="form-row row-flex">
        <view class="flex-spacer"></view>
        <view v-if="signImage" class="signature-row">
          <image :src="signImage" class="signature-thumb" />
          <button class="fill-helper-btn signature-btn" @click="gotoSign">{{ t('order.re_sign') }}</button>
        </view>
        <view v-else>
          <button class="fill-helper-btn" @click="gotoSign">{{ t('order.go_sign') }}</button>
        </view>
      </view>
    </view>

    <!-- 固定底部提交按钮 -->
    <view class="fixed-bottom-btn">
      <button class="fill-btn" @click="submitForm">{{ t('order.common_submit') }}</button>
    </view>
  </view>
</template>

<script>
import { useUserStore } from '@/store/user.js'
import { treatmentRecord } from '@/api/order.js'
import { uploadInfo } from '@/api/common.js'
import { resetSignature } from '@/api/user.js'
import { useI18n } from 'vue-i18n'
export default {
  data() {
    return {
      painIndex: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
      // purposeOptions: ['治疗按摩', '针灸'],
      // painTypeOptions: ['隐隐作痛', '刺痛', '劳累伴疼痛', '抽痛'],
    
      formData: {
        objective_list: [],   //治疗目的
        pain_mode: '',    //疼痛方式
        pain_value: '',    //疼痛指数
        type: '',         //是否有困难仰卧或者俯卧
        main_complaint: '',   //主诉
        inspect: '',  //检查
        symptom: '',   //症状
        part: '',      //部位
        method: '',    //治疗方法
        result: '',    //结果
        plan_day: '',   //治疗天数
        plan_ce: '',    //治疗次数
        describe: '',    //补充说明
        signature: '',    //签名文件
        patient_id: '',      //会员id
        file: null,
        fileName: '',
        good_id: null, // 新增：产品ID
        files: [], // 存储所有已上传文件
        file_id: [], // 存储所有已上传文件的id
        
        // 存储选择的id
        main_complaint_ids: [],  //主诉id
        inspect_ids: [],  //检查id
        symptom_ids: [],   //症状id
        part_ids: [],      //部位id
        method_ids: [],    //治疗方法id
        result_ids: [],    //结果id
      },
      planDayIndex: null,
      planTimesIndex: null,
      formCollapsed: false,
      collapse: {
        zhusuGroup: false
      },
      zhusuSelected: [],
      jianchaSelected: [],
      zhengzhuangSelected: [],
      currentDate: this.getToday(),

      memberInfo: {},    //会员信息
      productInfo: {},   //产品信息
      daysOptions: [1, 2, 3, 5, 7, 10, 14, 30],
      timesOptions: [1, 2, 3, 5, 7, 10],
      bodySelected: [],
      treatmentmethodSelected: [],
      resultSelected: [],
      signImage: '', // 当前签名图片
      selectedProducts: [], // 已选产品列表
      // shouldShowProductSelection: false, // 控制产品选择区域显示 - 移除这个静态属性，使用计算属性
    }
  },
  setup() {
    const { t } = useI18n() // 必须在 setup() 里
    const userStore = useUserStore()
    // 动态设置页面标题以支持国际化
    if (typeof uni !== 'undefined' && uni.setNavigationBarTitle) {
      uni.setNavigationBarTitle({
        title: t('order.title')
      })
    }
    return { t, userStore }
  },
  onReady() {
    // 进入页面时设置国际化标题
    if (typeof this.t === 'function') {
      uni.setNavigationBarTitle({
        title: this.t('order.title')
      })
    }
  },
  computed: {
    userStore() {
      return useUserStore()
    },
    userInfo() {
      return this.userStore.userInfo
    },
    purposeOptions() {
    const options = [
      this.t('order.purpose_massage'),
      this.t('order.purpose_acupuncture')
    ];
    
    // 只有从中药处方跳转过来时才显示中药选项
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    if (currentPage.options && currentPage.options.from === 'zhong') {
      options.push(this.t('order.purpose_medicine'));
    }
    
    return options;
  },
  painTypeOptions() {
    return [
      this.t('order.pain_type_1'),
      this.t('order.pain_type_2'),
      this.t('order.pain_type_3'),
      this.t('order.pain_type_4')
    ]
  },
  // 检查是否应该显示产品选择区域
  shouldShowProductSelection() {
    // 产品选择区域始终显示，不依赖治疗目的的选择
    return true;
  }
  },
  mounted() {
    if (this.userInfo.signature) {
      this.signImage = this.userInfo.signature;
      this.useUserSign = true;
    }
  },
  onShow() {
    // 监听签名图片回传
    uni.$once('signImage', (img) => {
      this.signImage = img;
    });
    // 监听会员选择事件
    uni.$once('memberSelected', (member) => {
      this.memberInfo = member;
      this.currentDate = this.getToday();
      this.formData.patient_id = member.id;
    });
    // 监听产品选择事件
    uni.$once('productSelected', (product) => {
      // 检查产品是否已经选择过
      const existingIndex = this.selectedProducts.findIndex(p => p.id === product.id);
      if (existingIndex === -1) {
        // 为产品添加默认type字段（假设为按摩产品）
        const productWithType = {
          ...product,
          type: product.type || '0' // 如果没有type字段，默认为按摩产品
        };
        
        // 添加新产品到列表
        this.selectedProducts.push(productWithType);
        // 更新formData中的产品ID列表
        this.formData.selected_products = this.selectedProducts.map(p => p.id);
        // 保持向后兼容，设置第一个产品的ID到good_id
        if (this.selectedProducts.length === 1) {
          this.formData.good_id = product.id;
        }
      } else {
        console.log('产品已存在，跳过添加');
      }
    });
    // 产品选择兜底
    const productKey = 'helper_selected_product';
    const localProduct = uni.getStorageSync(productKey);
    if (localProduct && typeof localProduct === 'object') {
      // console.log('从本地存储获取到产品:', localProduct);
      // 检查产品是否已经选择过
      const existingIndex = this.selectedProducts.findIndex(p => p.id === localProduct.id);
      if (existingIndex === -1) {
        // 为本地存储的产品添加默认type字段（假设为按摩产品）
        // 注意：这里可能需要根据实际情况调整默认类型
        const productWithType = {
          ...localProduct,
          type: localProduct.type || '0' // 如果没有type字段，默认为按摩产品
        };
        
        // 添加新产品到列表
        this.selectedProducts.push(productWithType);
        // 更新formData中的产品ID列表
        this.formData.selected_products = this.selectedProducts.map(p => p.id);
        // 保持向后兼容，设置第一个产品的ID到good_id
        if (this.selectedProducts.length === 1) {
          this.formData.good_id = localProduct.id;
        }
      } else {
        // console.log('本地存储产品已存在，跳过添加');
      }
      uni.removeStorageSync(productKey);
    }
    // 兜底：助手页刷新后回传
    const zhusuKey = 'helper_selected_mainComplaint';
    const localZhusu = uni.getStorageSync(zhusuKey);
    if (localZhusu && Array.isArray(localZhusu)) {
      this.zhusuSelected = localZhusu;
      this.formData.main_complaint = localZhusu.map(item => item.name || item.label || item).join('，');
      this.formData.main_complaint_ids = localZhusu.map(item => item.id || item);
      uni.removeStorageSync(zhusuKey);
    }
    // 检查
    const jianchaKey = 'helper_selected_examination';
    const localJiancha = uni.getStorageSync(jianchaKey);
    if (localJiancha && Array.isArray(localJiancha)) {
      this.jianchaSelected = localJiancha;
      this.formData.inspect = localJiancha.map(item => item.name || item.label || item).join('，');
      this.formData.inspect_ids = localJiancha.map(item => item.id || item);
      uni.removeStorageSync(jianchaKey);
    }

    // 症状
    const zhengzhuangKey = 'helper_selected_symptom';
    const localZhengzhuang = uni.getStorageSync(zhengzhuangKey);
    if (localZhengzhuang && Array.isArray(localZhengzhuang)) {
      this.zhengzhuangSelected = localZhengzhuang;
      this.formData.symptom = localZhengzhuang.map(item => item.name || item.label || item).join('，');
      this.formData.symptom_ids = localZhengzhuang.map(item => item.id || item);
      uni.removeStorageSync(zhengzhuangKey);
    }

    // 部位
    const bodyKey = 'helper_selected_area';
    const localBody = uni.getStorageSync(bodyKey);
    if (localBody && Array.isArray(localBody)) {
      this.bodySelected = localBody;
      this.formData.part = localBody.map(item => item.name || item.label || item).join('，');
      this.formData.part_ids = localBody.map(item => item.id || item);
      uni.removeStorageSync(bodyKey);
    }

    // 治疗方法
    const methodKey = 'helper_selected_method';
    const localMethod = uni.getStorageSync(methodKey);
    if (localMethod && Array.isArray(localMethod)) {
      this.treatmentmethodSelected = localMethod;
      this.formData.method = localMethod.map(item => item.name || item.label || item).join('，');
      this.formData.method_ids = localMethod.map(item => item.id || item);
      uni.removeStorageSync(methodKey);
    }

    // 结果
    const resultKey = 'helper_selected_outcome';
    const localResult = uni.getStorageSync(resultKey);
    if (localResult && Array.isArray(localResult)) {
      this.resultSelected = localResult;
      this.formData.result = localResult.map(item => item.name || item.label || item).join('，');
      this.formData.result_ids = localResult.map(item => item.id || item);
      uni.removeStorageSync(resultKey);
    }
    // 会员选择兜底
    const memberKey = 'helper_selected_member';
    const localMember = uni.getStorageSync(memberKey);
    if (localMember && typeof localMember === 'object') {
      this.memberInfo = localMember;
      this.currentDate = this.getToday();
      this.formData.patient_id = localMember.id;
      uni.removeStorageSync(memberKey);
    }
    // 你可以按需为其他类型（检查、症状等）添加类似逻辑
  },
  methods: {
    // 治疗目的多选
    togglePurpose(item) {
      const idx = this.formData.objective_list.indexOf(item);
      if (idx > -1) {
        // 取消选择治疗目的
        this.formData.objective_list.splice(idx, 1);
        
        // 如果取消的是针灸，清除所有针灸产品
        if (item === this.t('order.purpose_acupuncture')) {
          this.clearAcupunctureProducts();
        }
        // 如果取消的是治疗按摩，清除所有按摩产品
        else if (item === this.t('order.purpose_massage')) {
          this.clearMassageProducts();
        }
      } else {
        // 选择治疗目的
        this.formData.objective_list.push(item);
      }
    },
    // 疼痛方式单选
    selectPainType(item) {
      this.formData.pain_mode = item;
    },
    // 疼痛指数单选
    selectPainIndex(item) {
      this.formData.pain_value = item;
    },
    // 是否困难仰卧单选
    selectSleepy(val) {
      this.formData.type = val === '是' ? true : false;
    },

    // 表单验证
    validateForm() {
      // 验证治疗目的
      // if (this.formData.objective_list.length === 0) {
      //   uni.showToast({ title: this.t('order.select_purpose_first'), icon: 'none' });
      //   return false;
      // }
      
      // // 验证检查内容
      // if (!this.formData.inspect || this.formData.inspect.trim() === '') {
      //   uni.showToast({ title: '请填写检查内容', icon: 'none' });
      //   return false;
      // }
      
      // // 验证症状
      // if (!this.formData.symptom || this.formData.symptom.trim() === '') {
      //   uni.showToast({ title: '请填写症状', icon: 'none' });
      //   return false;
      // }
      
      // // 验证部位
      // if (!this.formData.part || this.formData.part.trim() === '') {
      //   uni.showToast({ title: '请填写部位', icon: 'none' });
      //   return false;
      // }
      
      // // 验证治疗方法
      // if (!this.formData.method || this.formData.method.trim() === '') {
      //   uni.showToast({ title: '请填写治疗方法', icon: 'none' });
      //   return false;
      // }
      
      // // 验证结果
      // if (!this.formData.result || this.formData.result.trim() === '') {
      //   uni.showToast({ title: '请填写结果', icon: 'none' });
      //   return false;
      // }
      
      // 验证签名
      if (!this.formData.signature) {
        uni.showToast({ title: '请先完成签名', icon: 'none' });
        return false;
      }
      
      return true;
    },

    // 提交表单并上传签名图片
    async submitForm() {
      this.formData.signature = this.userInfo.signature_path;
      this.formData.file_id = this.formData.files.map(file => file.id);
      this.formData.objective = this.formData.objective_list.join(';')
      console.log('提交表单数据:', this.formData);

      // 表单验证
      if (!this.validateForm()) {
        return;
      }
      
      // 合并产品和中药的ID列表
      const allProductIds = [
        ...(this.formData.selected_products || []),
        ...(this.formData.selected_medicines || [])
      ];
      
      // 如果有选择治疗目的，但没有任何产品（包括中药），则提示选择
      if (this.formData.objective_list.length > 0 && allProductIds.length === 0) {
        uni.showToast({ title: this.t('order.select_product'), icon: 'error' })
        return;
      }
      
      console.log('提交表单数据:', this.formData);

      if (!this.formData.patient_id) {
        uni.showToast({ title: this.t('order.select_member'), icon: 'error' })
        return;
      }
      
      // 清理空值
      Object.keys(this.formData).forEach((key) => {
        if (this.formData[key] === '') {
          this.formData[key] = null;
        }
      });
      
      console.log("********this.formData********", this.formData)
      
      // 数据提交
      try {
        const res = await treatmentRecord(this.formData)
        console.log("res", res)
        if (res.code == 200) {
            uni.showToast({ title: res.message, icon: 'success' })
            uni.switchTab({
              url: '/pages/my/index'
            });
        } else {
            uni.showToast({ title: res.message, icon: 'error' })
        }
      } catch (error) {
        console.error('提交失败:', error);
        uni.showToast({ title: '提交失败，请重试', icon: 'error' })
      }
    },

    gotoSign() {
      // 跳转签名页，签名完成后回传图片
      uni.navigateTo({
        url: '/pages/order/sign',
        events: {
          signImage: (img) => {
            this.signImage = img;
            this.useUserSign = false;
            this.updateUserSign(img);
          }
        }
      });
    },
    async updateUserSign(img) {
      const res = await resetSignature({ 
        signature: img, 
        user_id: this.userInfo.id 
      })
      console.log(res)
      if (res.code == 200) {
        this.userInfo.signFile = res.result.url;
        this.userInfo.signature = res.result.url;
        this.userInfo.signature_path = res.result.save_path;
        uni.setStorageSync('userInfo', this.userInfo);
        this.signImage = res.result.url;
      }
    },
    getToday() {
      const d = new Date();
      const y = d.getFullYear();
      const m = (d.getMonth() + 1).toString().padStart(2, '0');
      const day = d.getDate().toString().padStart(2, '0');
      return `${y}-${m}-${day}`;
    },
    gotoMemberSelect() {
      const storageKey = 'helper_selected_member';
      uni.removeStorageSync(storageKey);
      uni.navigateTo({
        url: '/pages/order/member-select',
        events: {
          memberSelected: (member) => {
            this.memberInfo = member;
            this.currentDate = this.getToday();
            this.formData.patient_id = member.id;
            uni.removeStorageSync(storageKey);
          }
        }
      });
    },

    gotoProductSelect(type) {
      // 检查是否选择了对应的治疗目的
      if (type === '0' && !this.formData.objective_list.includes(this.t('order.purpose_massage'))) {
        uni.showToast({ 
          title: this.t('order.select_massage_purpose_first'), 
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      if (type === '1' && !this.formData.objective_list.includes(this.t('order.purpose_acupuncture'))) {
        uni.showToast({ 
          title: this.t('order.select_acupuncture_purpose_first'), 
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      const storageKey = 'helper_selected_product';
      uni.removeStorageSync(storageKey);
      
      // 构建跳转URL，携带type参数
      let url = '/pages/order/product-select';
      if (type !== '') {
        url += `?type=${type}`;
      }
      
      uni.navigateTo({
        url: url,
        events: {
          productSelected: (product) => {
            // 检查产品是否已经选择过
            const existingIndex = this.selectedProducts.findIndex(p => p.id === product.id);
            if (existingIndex === -1) {
              // 为产品添加type字段，用于后续识别产品类型
              const productWithType = {
                ...product,
                type: type // 直接使用字符串类型，不进行parseInt转换
              };
              
              // 添加新产品到列表
              this.selectedProducts.push(productWithType);
              // 更新formData中的产品ID列表
              this.formData.selected_products = this.selectedProducts.map(p => p.id);
              // 保持向后兼容，设置第一个产品的ID到good_id
              if (this.selectedProducts.length === 1) {
                this.formData.good_id = product.id;
              }
              
              console.log('产品已添加，包含type字段:', productWithType);
              console.log('产品类型详情:', {
                originalType: type,
                productType: productWithType.type,
                typeOf: typeof productWithType.type
              });
            } else {
              uni.showToast({ 
                title: this.t('order.product_already_selected'), 
                icon: 'none' 
              });
            }
            uni.removeStorageSync(storageKey);
          }
        }
      });
    },
    chooseFile() {
      uni.chooseFile({
        count: 9, // 支持多选
        success: (res) => {
          const files = res.tempFiles;
          console.log('files', files);
          files.forEach(file => {
            this.uploadAndSaveFile(file);
          });
        }
      });
    },
    async uploadAndSaveFile(file) {
      try {
        // file: uni.chooseFile返回的单个文件对象
        const res = await uploadInfo(file);
        console.log('res', res);
        this.formData.files.push({
          name: res.result.name,      // 原始文件名
          url: res.result.url,        // 文件访问地址
          id: res.result.id,          // 可选：数据库ID
          save_name: res.result.save_name // 可选：UUID文件名
        });
      } catch (e) {
        uni.showToast({ title: t('common.upload_failed'), icon: 'none' });
      }
    },
    removeFile(idx) {
      this.formData.files.splice(idx, 1);
    },
    onPlanDayChange(e) {
      this.planDayIndex = e.detail.value;
      this.formData.plan_day = this.daysOptions[this.planDayIndex];
    },
    onPlanTimesChange(e) {
      this.planTimesIndex = e.detail.value;
      this.formData.plan_ce = this.timesOptions[this.planTimesIndex];
    },
    gotoZhusuHelper() {
      const storageKey = 'helper_selected_mainComplaint';
      uni.removeStorageSync(storageKey); // 跳转前清空
      uni.navigateTo({
        url: '/pages/order/zhuShouHelper?type=mainComplaint&title=' + encodeURIComponent(this.t('order.main_complaint')) + '&selected=' + encodeURIComponent(JSON.stringify(this.zhusuSelected.map(id => ({ id })))),
        events: {
          helperSelected: (selected) => {
            this.zhusuSelected = selected;
            this.formData.main_complaint = selected.map(item => item.name || item.label || item).join('，');
            this.formData.main_complaint_ids = selected.map(item => item.id || item);
            uni.removeStorageSync(storageKey);
          }
        }
      });
    },
    gotoJianchaHelper() {
      const storageKey = 'helper_selected_examination';
      uni.removeStorageSync(storageKey);
      uni.navigateTo({
        url: '/pages/order/zhuShouHelper?type=examination&title=' + encodeURIComponent(this.t('order.inspect')) + '&selected=' + encodeURIComponent(JSON.stringify(this.jianchaSelected.map(id => ({ id })))),
        events: {
          helperSelected: (selected) => {
            this.jianchaSelected = selected;
            this.formData.inspect = selected.map(item => item.name || item.label || item).join('，');
            this.formData.inspect_ids = selected.map(item => item.id || item);
            uni.removeStorageSync(storageKey);
          }
        }
      });
    },
    gotoZhengzhuangHelper() {
      const storageKey = 'helper_selected_symptom';
      uni.removeStorageSync(storageKey);
      uni.navigateTo({
        url: '/pages/order/zhuShouHelper?type=symptom&title=' + encodeURIComponent(this.t('order.symptom')) + '&selected=' + encodeURIComponent(JSON.stringify(this.zhengzhuangSelected.map(id => ({ id })))),
        events: {
          helperSelected: (selected) => {
            this.zhengzhuangSelected = selected;
            this.formData.symptom = selected.map(item => item.name || item.label || item).join('，');
            this.formData.symptom_ids = selected.map(item => item.id || item);
            uni.removeStorageSync(storageKey);
          }
        }
      });
    },
    gotoBodyHelper() {
      const storageKey = 'helper_selected_area';
      uni.removeStorageSync(storageKey);
      uni.navigateTo({
        url: '/pages/order/zhuShouHelper?type=area&title=' + encodeURIComponent(this.t('order.part')) + '&selected=' + encodeURIComponent(JSON.stringify(this.bodySelected.map(id => ({ id })))),
        events: {
          helperSelected: (selected) => {
            this.bodySelected = selected;
            this.formData.part = selected.map(item => item.name || item.label || item).join('，');
            this.formData.part_ids = selected.map(item => item.id || item);
            uni.removeStorageSync(storageKey);
          }
        }
      });
    },
    gotoTreatmentmethodHelper() {
      const storageKey = 'helper_selected_method';
      uni.removeStorageSync(storageKey);
      uni.navigateTo({
        url: '/pages/order/zhuShouHelper?type=method&title=' + encodeURIComponent(this.t('order.method')) + '&selected=' + encodeURIComponent(JSON.stringify(this.treatmentmethodSelected.map(id => ({ id })))),
        events: {
          helperSelected: (selected) => {
            this.treatmentmethodSelected = selected;
            this.formData.method = selected.map(item => item.name || item.label || item).join('，');
            this.formData.method_ids = selected.map(item => item.id || item);
            uni.removeStorageSync(storageKey);
          }
        }
      });
    },
    gotoResultHelper() {
      const storageKey = 'helper_selected_outcome';
      uni.removeStorageSync(storageKey);
      uni.navigateTo({
        url: '/pages/order/zhuShouHelper?type=outcome&title=' + encodeURIComponent(this.t('order.result')) + '&selected=' + encodeURIComponent(JSON.stringify(this.resultSelected.map(id => ({ id })))),
        events: {
          helperSelected: (selected) => {
            this.resultSelected = selected;
            this.formData.result = selected.map(item => item.name || item.label || item).join('，');
            this.formData.result_ids = selected.map(item => item.id || item);
            uni.removeStorageSync(storageKey);
          }
        }
      });
    },
    removeProduct(index) {
      // 移除选中的产品
      this.selectedProducts.splice(index, 1);
      // 更新formData中的产品ID列表
      this.formData.selected_products = this.selectedProducts.map(p => p.id);
      // 更新good_id
      if (this.selectedProducts.length > 0) {
        this.formData.good_id = this.selectedProducts[0].id;
      } else {
        this.formData.good_id = null;
      }
      uni.removeStorageSync('helper_selected_product'); // 清除本地缓存
    },
    clearAcupunctureProducts() {
      // 清除所有针灸产品
      const acupunctureProducts = this.selectedProducts.filter(product => {
        // 这里需要根据产品的type字段来判断是否为针灸产品
        // 假设产品有type字段，type=1表示针灸产品
        return product.type === '1' || product.type === 1;
      });
      
      if (acupunctureProducts.length > 0) {
        // 从selectedProducts中移除针灸产品
        this.selectedProducts = this.selectedProducts.filter(product => {
          return product.type !== '1' && product.type !== 1;
        });
        
        // 更新formData中的产品ID列表
        this.formData.selected_products = this.selectedProducts.map(p => p.id);
        
        // 更新good_id
        if (this.selectedProducts.length > 0) {
          this.formData.good_id = this.selectedProducts[0].id;
        } else {
          this.formData.good_id = null;
        }
        
      }
    },
    clearMassageProducts() {
      // 清除所有按摩产品
      const massageProducts = this.selectedProducts.filter(product => {
        // 这里需要根据产品的type字段来判断是否为按摩产品
        // 假设产品有type字段，type=0表示按摩产品
        return product.type === '0' || product.type === 0;
      });
      
      if (massageProducts.length > 0) {
        // 从selectedProducts中移除按摩产品
        this.selectedProducts = this.selectedProducts.filter(product => {
          return product.type !== '0' && product.type !== 0;
        });
        
        // 更新formData中的产品ID列表
        this.formData.selected_products = this.selectedProducts.map(p => p.id);
        
        // 更新good_id
        if (this.selectedProducts.length > 0) {
          this.formData.good_id = this.selectedProducts[0].id;
        } else {
          this.formData.good_id = null;
        }
        
      }
    },
    getProductTypeText(type) {
      // 调试信息
      console.log('产品类型判断:', {
        type: type,
        typeOf: typeof type,
        typeString: String(type),
        typeNumber: Number(type)
      });
      
      // 统一转换为字符串进行比较，避免类型不匹配问题
      const typeStr = String(type);
      
      if (typeStr === '0') {
        return this.t('order.purpose_massage');
      } else if (typeStr === '1') {
        return this.t('order.purpose_acupuncture');
      } else {
        console.warn('未知的产品类型:', type, '类型:', typeof type);
        return this.t('order.unknown');
      }
    }
  }
}
</script>

<style scoped>
.container {
  background: #fff;
  min-height: 100vh;
  padding-bottom: 140rpx;
  /* 给底部按钮留空间 */
}

.card {
  background: #fafafa;
  margin: 24rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx #eee;
  padding: 24rpx;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.info view {
  font-size: 28rpx;
  color: #444;
  margin-bottom: 4rpx;
}

.form-section {
  margin: 0 24rpx 24rpx 24rpx;
  background: #f5f5f5;
  border-radius: 12rpx;
  padding: 16rpx;
  box-sizing: border-box;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

/* 只让产品选择和签名按钮在form-row.row-flex内上下居中 */
.form-row.row-flex {
  flex-direction: row;
  align-items: center;
}

.form-row.row-flex .fill-helper-btn,
.form-row.row-flex .signature-btn {
  align-self: center;
}

.collapse-header {
  cursor: pointer;
  user-select: none;
  display: flex;
  align-items: center;
  padding: 12rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.collapse-arrow {
  margin-left: 12rpx;
  color: #888;
  font-size: 24rpx;
  margin-right: 12rpx;
}

.form-row {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 24rpx;
  flex-wrap: wrap;
  justify-content: center;
  min-height: 80rpx;
}

.row-flex {
  flex-direction: row !important;
  align-items: center !important;
  margin-bottom: 12rpx !important;
}

.form-label.full-width {
  width: 100%;
  font-weight: bold;
  color: #1976d2;
  font-size: 26rpx;
  margin-bottom: 12rpx;
}

.select-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin-top: 8rpx;
}

.select-group.left-align {
  justify-content: flex-start;
}

.select-item {
  padding: 10rpx 28rpx;
  border-radius: 20rpx;
  background: #e3eaf7;
  color: #1976d2;
  font-size: 24rpx;
  margin-right: 12rpx;
  margin-bottom: 8rpx;
  border: 1rpx solid #e3eaf7;
  transition: all 0.2s;
}

.select-item.selected {
  background: #1976d2;
  color: #fff;
  border: 1rpx solid #1976d2;
}

.fixed-bottom-btn {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  padding: 16rpx 24rpx 32rpx 24rpx;
  z-index: 100;
  box-shadow: 0 -2rpx 8rpx #eee;
}

.fill-btn {
  width: 100%;
  background: #1976d2;
  color: #fff;
  border-radius: 8rpx;
  font-size: 30rpx;
  height: 80rpx;
  line-height: 80rpx;
  display: block;
}

.form-textarea {
  width: 100%;
  padding: 10rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  margin-top: 12rpx;
  margin-bottom: 16rpx;
  box-sizing: border-box;
  max-width: 100%;
}

.fill-helper-btn {
  background: #1976d2;
  color: #fff;
  border-radius: 8rpx;
  font-size: 26rpx;
  padding: 8rpx 20rpx;
  margin-left: 0;
  margin-right: 0;
  height: 56rpx;
  line-height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
}

.flex-spacer {
  flex: 1;
}

.form-label {
  font-weight: bold;
  color: #1976d2;
  font-size: 26rpx;
  margin-bottom: 0;
}

.signature-row {
  display: flex;
  align-items: center;
  width: 100%;
  position: relative;
  min-height: 48px;
}

.signature-thumb {
  display: block;
  margin: 0 auto;
  width: 30vw;
  max-width: 160px;
  min-width: 80px;
  height: 40px;
  object-fit: contain;
  flex-shrink: 0;
  /* 去掉边框 */
  border: none;
}

.signature-btn {
  margin-left: auto;
  /* 靠右 */
}

.member-btn {
  position: absolute;
  right: 16px;
  top: 16px;
  z-index: 2;
  background: #007aff;
  color: #fff;
  border-radius: 6px;
  padding: 0 16px;
  height: 32px;
  line-height: 32px;
  font-size: 14px;
}

.member-popup {
  width: 80vw;
  max-width: 340px;
  background: #fff;
  border-radius: 10px;
  padding: 16px;
}

.product-show {
  display: flex;
  align-items: center;
  width: 100%;
}

.product-info-group {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.product-btn-right {
  margin-left: auto;
  flex-shrink: 0;
}

.product-thumb {
  width: 60px;
  height: 40px;
  object-fit: cover;
  border-radius: 6px;
}

.product-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.product-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.product-meta {
  display: flex;
  gap: 8px;
  font-size: 14px;
  color: #888;
}

.product-price {
  color: #e54d42;
  font-weight: bold;
}

.product-duration {
  color: #007aff;
}

.product-type {
  font-size: 12px;
  color: #666;
  margin-left: 8px;
}

.debug-info {
  font-size: 10px;
  color: #999;
  margin-left: 4px;
}

.upload-area {
  width: 100%;
  min-height: 60px;
  border: 1px dashed #bbb;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #888;
  background: #fafafa;
  margin-top: 12rpx;
  margin-bottom: 16rpx;
  cursor: pointer;
}

.custom-picker {
  min-width: 36px;
  max-width: 44px;
  padding: 0 10rpx;
  height: 48rpx;
  line-height: 48rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  background: #fff;
  display: flex;
  align-items: center;
  position: relative;
  color: #1976d2;
  font-size: 26rpx;
  cursor: pointer;
  margin: 0 4rpx;
  justify-content: space-between;
  box-sizing: border-box;
  overflow: hidden;
}

.custom-picker .arrow {
  margin-left: 0;
  margin-right: 0;
  font-size: 22rpx;
  color: #888;
  margin-left: auto;
}

.custom-picker:active,
.custom-picker:hover {
  border-color: #1976d2;
  background: #e3eaf7;
}

.uploaded-file {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8rpx 12rpx;
  background: #e0f2f7;
  border-radius: 8rpx;
  margin-bottom: 8rpx;
  font-size: 24rpx;
  color: #333;
}

.file-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 20rpx;
}

.delete-btn {
  background: #ff4d4f;
  color: #fff;
  border-radius: 6rpx;
  padding: 4rpx 18rpx;
  font-size: 22rpx;
  line-height: 28rpx;
  border: none;
  white-space: nowrap;
  margin-left: 12rpx;
  min-width: 60rpx;
  min-height: 36rpx;
  box-shadow: 0 2px 6px rgba(255, 77, 79, 0.08);
  transition: background 0.2s;
}

.delete-btn:active {
  background: #d9363e;
}

.section-header {
  display: flex;
  align-items: center;
  padding: 12rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-left: 12rpx;
}

.selected-products-list {
  margin-top: 12rpx;
  padding: 12rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.selected-product-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12rpx 0;
  border-bottom: 1rpx dashed #eee;
}

.selected-product-item:last-child {
  border-bottom: none;
}

.remove-product-btn {
  background: #ff4d4f;
  color: #fff;
  border-radius: 6rpx;
  padding: 4rpx 18rpx;
  font-size: 22rpx;
  line-height: 28rpx;
  border: none;
  white-space: nowrap;
  margin-left: 12rpx;
  min-width: 60rpx;
  min-height: 36rpx;
  box-shadow: 0 2px 6px rgba(255, 77, 79, 0.08);
  transition: background 0.2s;
}

.remove-product-btn:active {
  background: #d9363e;
}

.product-selection-buttons {
  display: flex;
  gap: 16rpx;
  margin-top: 16rpx;
  padding-top: 16rpx;
  border-top: 1rpx dashed #eee;
}

.disabled-btn {
  opacity: 0.6;
  cursor: not-allowed;
}

.selection-tip {
  margin-top: 16rpx;
  padding: 12rpx 20rpx;
  background: #e0f2f7;
  border-radius: 8rpx;
  border: 1rpx dashed #bbb;
  color: #888;
  font-size: 24rpx;
  text-align: center;
}

.tip-text {
  font-size: 26rpx;
  color: #888;
}
</style>